package cn.lopr.im.android.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;

import org.java_websocket.handshake.ServerHandshake;

import cn.lopr.im.android.common.Constant;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.db.helper.DaoUtilsStore;
import cn.lopr.im.android.mvp.view.activities.LoginActivity;
import cn.lopr.im.android.utils.DateUtil;
import cn.lopr.im.android.utils.IMWebSocketClient;

public class MessageService extends Service {

    static MessageService messageService;

    private String phone = null;

    private IMWebSocketClientBinder binder = new IMWebSocketClientBinder();

    public static class IMWebSocketClientBinder extends Binder {
        public MessageService getService() {
            if (messageService == null) {
                messageService = new MessageService();
            }
            return messageService;
        }
    }

    public MessageService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("MessageService", "onCreate: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        Log.e("MessageService", "onStartCommand: ");
        if (intent != null) {  // 有时候意图传递是空的
            this.phone = intent.getStringExtra("phone");
        }
        if (this.phone == null) {
            return super.onStartCommand(intent, flags, startId);
        }

        IMWebSocketClient.connect(new IMWebSocketClient.WebSocketListener() {
            @Override
            public void onOpen(ServerHandshake handshake) {
                Message messageBean = new Message().setDate(DateUtil.getTime())
                        .setFromUser(phone).setType(0);

                IMWebSocketClient.getWebSocketClient().send(new Gson().toJson(messageBean));
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {

            }

            @Override
            public void onMessage(String message) {
                Log.e("MessageService: ", "onMessage: " + message + " : " + phone);
                Message messageBean = new Gson().fromJson(message, Message.class);
                Constant.MessageType typeByCode = Constant.MessageType.getTypeByCode(messageBean.getType());
                switch (typeByCode) {
                    case SEND_TO_USER:
                        if (messageBean.getMsg().equals("relogin") && messageBean.getFromUser().equals(phone)) {
                            IMWebSocketClient.disConnect();
                            Intent dialogIntent = new Intent(getBaseContext(), LoginActivity.class);
                            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            getApplication().startActivity(dialogIntent);
                            Toast.makeText(MessageService.this, "该用户已被登录，请重新登录", Toast.LENGTH_SHORT).show();
                        } else {
                            DaoUtilsStore.getInstance().getMessageDaoUtils().insert(messageBean.setIsRead(0));
                            Intent intent = new Intent("cn.lopr.im.android.servicecallback.content");
                            intent.putExtra("message", messageBean);
                            sendBroadcast(intent);
                            Log.i("Bean", "onMessage: sendBroadcast " + messageBean);
                        }
                        break;
                    case SEND_ADD:  //单聊信息和单点登录信息
                        DaoUtilsStore.getInstance().getMessageDaoUtils().insert(messageBean.setIsRead(0));
                        Intent intent = new Intent("cn.lopr.im.android.servicecallback.content.add");
                        sendBroadcast(intent);
                        break;
                }
            }

            @Override
            public void onError(Exception ex) {
            }
        });

        //return super.onStartCommand(intent, flags, startId);
        return START_REDELIVER_INTENT;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return this.binder;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }
}